package com.ts.service.achievement.impl;

import com.ts.dto.MemberDTO;
import com.ts.dto.SoftwareCopyrightDTO;
import com.ts.entity.Member;
import com.ts.entity.SoftwareCopyright;
import com.ts.mapper.achievement.SoftwareCopyrightMapper;
import com.ts.mapper.achievement.SoftwareCopyrightMemberMapper;
import com.ts.service.achievement.SoftwareCopyrightService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 软件著作权服务实现
 */
@Service
@Slf4j
public class SoftwareCopyrightServiceImpl implements SoftwareCopyrightService {

    private final SoftwareCopyrightMapper softwareCopyrightMapper;
    private final SoftwareCopyrightMemberMapper softwareCopyrightMemberMapper;

    /**
     * 构造器注入
     */
    @Autowired
    public SoftwareCopyrightServiceImpl(SoftwareCopyrightMapper softwareCopyrightMapper,
                                        SoftwareCopyrightMemberMapper softwareCopyrightMemberMapper) {
        this.softwareCopyrightMapper = softwareCopyrightMapper;
        this.softwareCopyrightMemberMapper = softwareCopyrightMemberMapper;
    }

    /**
     * 保存软件著作权
     */
    @Transactional
    @Override
    public Long save(SoftwareCopyrightDTO softwareCopyrightDTO) {
        log.info("=== Service层开始保存 ===");
        log.info("Service接收到的developmentCompletionTime: {}", softwareCopyrightDTO.getDevelopmentCompletionTime());

        // 数据验证
        if (softwareCopyrightDTO.getDevelopmentCompletionTime() == null) {
            log.error("Service层：开发完成时间为空！");
            throw new IllegalArgumentException("开发完成时间不能为空");
        }

        SoftwareCopyright softwareCopyright = new SoftwareCopyright();
        BeanUtils.copyProperties(softwareCopyrightDTO, softwareCopyright);

        log.info("转换后的实体developmentCompletionTime: {}", softwareCopyright.getDevelopmentCompletionTime());
        // 确保ID为null，让数据库自增
        softwareCopyright.setId(null);
        // 设置公共字段
        LocalDateTime now = LocalDateTime.now();
        softwareCopyright.setCreateTime(now);
        softwareCopyright.setUpdateTime(now);
        softwareCopyright.setCreateBy(11L);
        softwareCopyright.setUpdateBy(11L);
        softwareCopyright.setDeleted(0);

        log.info("开始插入软件著作权数据...");
        softwareCopyrightMapper.insert(softwareCopyright);

        log.info("软件著作权插入完成，生成的ID: {}", softwareCopyright.getId());

        // 补充：保存成员信息
        saveMembers(softwareCopyrightDTO.getMemberList(), softwareCopyright.getId());

        // 返回数据库生成的ID
        return softwareCopyright.getId();
    }

    /**
     * 根据ID查询
     */
    @Override
    public SoftwareCopyrightDTO getById(Long id) {
        SoftwareCopyright softwareCopyright = softwareCopyrightMapper.selectById(id);
        if (softwareCopyright == null) {
            return null;
        }

        SoftwareCopyrightDTO dto = new SoftwareCopyrightDTO();
        BeanUtils.copyProperties(softwareCopyright, dto);

        // 补充：查询成员信息
        List<Member> members = softwareCopyrightMemberMapper.getByProjectId(id);
        List<MemberDTO> memberDTOs = members.stream()
                .map(member -> {
                    MemberDTO memberDTO = new MemberDTO();
                    BeanUtils.copyProperties(member, memberDTO);
                    return memberDTO;
                })
                .collect(Collectors.toList());
        dto.setMemberList(memberDTOs);

        return dto;
    }

    /**
     * 更新软件著作权
     */
    @Transactional
    @Override
    public void update(SoftwareCopyrightDTO softwareCopyrightDTO) {
        SoftwareCopyrightDTO existing = getById(softwareCopyrightDTO.getId());
        if (existing == null) {
            throw new RuntimeException("软件著作权记录不存在或已被删除");
        }
        SoftwareCopyright softwareCopyright = new SoftwareCopyright();
        BeanUtils.copyProperties(softwareCopyrightDTO, softwareCopyright);

        // 设置更新字段
        softwareCopyright.setUpdateTime(LocalDateTime.now());
        softwareCopyright.setUpdateBy(11L); // 实际项目中从登录信息获取

        softwareCopyrightMapper.update(softwareCopyright);

        // 补充：更新成员信息（先删除后新增）
        softwareCopyrightMemberMapper.deleteByProjectId(softwareCopyrightDTO.getId());
        saveMembers(softwareCopyrightDTO.getMemberList(), softwareCopyrightDTO.getId());
    }

    /**
     * 删除软件著作权
     */
    @Transactional
    @Override
    public void delete(Long id) {
        // 补充：先删除成员信息
        softwareCopyrightMemberMapper.deleteByProjectId(id);
        // 再删除主表
        softwareCopyrightMapper.deleteById(id);
    }

    /**
     * 查询所有软件著作权
     */
    @Override
    public List<SoftwareCopyrightDTO> getAll() {
        List<SoftwareCopyright> list = softwareCopyrightMapper.selectAll();
        return list.stream().map(entity -> {
            SoftwareCopyrightDTO dto = new SoftwareCopyrightDTO();
            BeanUtils.copyProperties(entity, dto);

            // 补充：为每个软著查询成员信息
            List<Member> members = softwareCopyrightMemberMapper.getByProjectId(entity.getId());
            List<MemberDTO> memberDTOs = members.stream()
                    .map(member -> {
                        MemberDTO memberDTO = new MemberDTO();
                        BeanUtils.copyProperties(member, memberDTO);
                        return memberDTO;
                    })
                    .collect(Collectors.toList());
            dto.setMemberList(memberDTOs);

            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 根据软件名称查询
     */
    @Override
    public List<SoftwareCopyrightDTO> getBySoftwareName(String softwareName) {
        List<SoftwareCopyright> list = softwareCopyrightMapper.selectBySoftwareName(softwareName);
        return list.stream().map(entity -> {
            SoftwareCopyrightDTO dto = new SoftwareCopyrightDTO();
            BeanUtils.copyProperties(entity, dto);

            // 补充：查询成员信息
            List<Member> members = softwareCopyrightMemberMapper.getByProjectId(entity.getId());
            List<MemberDTO> memberDTOs = members.stream()
                    .map(member -> {
                        MemberDTO memberDTO = new MemberDTO();
                        BeanUtils.copyProperties(member, memberDTO);
                        return memberDTO;
                    })
                    .collect(Collectors.toList());
            dto.setMemberList(memberDTOs);

            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 保存软著成员信息
     */
    private void saveMembers(List<MemberDTO> memberList, Long projectId) {
        if (memberList != null && !memberList.isEmpty()) {
            List<Member> members = memberList.stream()
                    .map(memberDTO -> {
                        Member member = new Member();
                        BeanUtils.copyProperties(memberDTO, member);
                        member.setProjectId(projectId); // 设置关联的项目ID
                        return member;
                    })
                    .collect(Collectors.toList());
            softwareCopyrightMemberMapper.batchInsert(members);
        }
    }
}